package cn.gogpay.duoim.sdk.service;

import cn.gogpay.duoim.sdk.config.IMContext;
import cn.gogpay.duoim.sdk.constant.IMHeaders;
import cn.gogpay.duoim.sdk.constant.IMRespCode;
import cn.gogpay.duoim.sdk.exception.IMSDKException;
import cn.gogpay.duoim.sdk.model.v3.base.IMCertificate;
import cn.gogpay.duoim.sdk.network.IMHttpFactory;
import cn.gogpay.duoim.sdk.service.v3.*;
import cn.gogpay.duoim.sdk.util.IMUtil;
import cn.hutool.core.util.StrUtil;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

public class IMApiFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(IMApiFactory.class);

    public static IMAuthService AUTH;

    public static IMAuthV3Service AUTH_V3;

    public static IMGroupService GROUP;
    public static IMGroupV3Service GROUP_V3;

    public static IMMessageService MESSAGE;
    public static IMMessageV3Service MESSAGE_V3;

    public static IMConversationService CONVERSATION;
    public static IMConversationV3Service CONVERSATION_V3;

    public static IMUserService USER;
    public static IMUserV3Service USER_V3;

    private static IMContext CONTEXT;

    public static void init(IMContext context) {
        LOGGER.info("多多IM即时通信SDK初始化：{}", context.toString());
        CONTEXT = context;
        AUTH = new IMAuthService();
        AUTH_V3 = new IMAuthV3Service();
        GROUP = new IMGroupService();
        GROUP_V3 = new IMGroupV3Service();
        MESSAGE = new IMMessageService();
        MESSAGE_V3 = new IMMessageV3Service();
        CONVERSATION = new IMConversationService();
        CONVERSATION_V3 = new IMConversationV3Service();
        USER = new IMUserService();
        USER_V3 = new IMUserV3Service();
    }

    public static String buildUrl(String url) {
        return CONTEXT.getApiServiceAddr() + url;
    }

    public static String buildSecret() {
        return CONTEXT.getApiServiceSecret();
    }

    public static Request buildRequest(String params, String path) {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody requestBody = RequestBody.create(mediaType, params);
        String url = buildUrl(path);
        return new Request.Builder()
                .url(url)
                .addHeader("Content-Type", "application/json")
                .post(requestBody)
                .build();
    }

    public static Request buildLoginRequest(String token, String param, String path) {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody requestBody = RequestBody.create(mediaType, param);
        String url = buildUrl(path);
        return new Request.Builder()
                .url(url)
                .addHeader("Content-Type", "application/json")
                .addHeader("token", token)
                .post(requestBody)
                .build();
    }

    public static Request buildCertifiedRequest(IMCertificate certificate, String param, String path) {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody requestBody = RequestBody.create(mediaType, param);
        String url = buildUrl(path);
        Request.Builder builder = new Request.Builder()
                .url(url)
                .addHeader("Content-Type", "application/json");
        String operationId;
        if (StrUtil.isNotEmpty(certificate.getOperationId())) {
            operationId = certificate.getOperationId();
        } else {
            operationId = IMUtil.genOperationID();
        }
        builder.addHeader(IMHeaders.OPERATION_ID, operationId);
        if (StrUtil.isNotEmpty(certificate.getImToken())) {
            builder.addHeader(IMHeaders.TOKEN, certificate.getImToken());
        }
        return builder.post(requestBody).build();
    }

    public static String callRequest(Request request) {
        OkHttpClient client = IMHttpFactory.client();
        Call call = client.newCall(request);
        String data;
        try (Response response = call.execute()) {
            boolean successful = response.isSuccessful();
            ResponseBody body = response.body();
            if (successful && Objects.nonNull(body)) {
                data = body.string();
            } else {
                String string = response.toString();
                throw new IMSDKException(string);
            }
        } catch (Exception e) {
            LOGGER.error("多多IM即时通信接口请求异常", e);
            String message = e.getMessage();
            if (message == null) {
                message = "多多IM即时通信接口请求异常";
            }
            throw new IMSDKException(IMRespCode.api(), message);
        }
        return data;
    }

    public static void callRequest(Request request, Callback callback) {
        OkHttpClient client = IMHttpFactory.client();
        Call call = client.newCall(request);
        call.enqueue(callback);
    }
}
